<template>
  <div>
    <el-space direction="vertical" alignment="left" style="width: 100%">
      <el-card>
        <el-form ref="searchFormComponents" :model="searchForm" inline>
          <el-form-item label="姓名" prop="nickname">
            <el-input v-model="searchForm.nickname" placeholder="请输入姓名" clearable></el-input>
          </el-form-item>
          <el-form-item label="">
            <el-button type="primary" :icon="Search" @click="search">搜索</el-button>
            <el-button :icon="Refresh" @click="resetSearch">重置</el-button>
          </el-form-item>
        </el-form>
        <el-space>
          <el-button type="primary" @click="add" :icon="Plus">新增</el-button>
          <el-button type="danger" :icon="Delete" @click="batchDelete(null)" :disabled="selectionRows.length<=0">批量删除</el-button>
        </el-space>
      </el-card>
      <el-card>
        <el-table ref="tableComponents"
                  :data="listData"
                  tooltip-effect="dark"
                  style="width: 100%"
                  @selection-change="selectionChange"
                  border>
          <el-table-column type="selection" width="55"></el-table-column>
          <el-table-column prop="id" label="ID" width="50"></el-table-column>
          <el-table-column prop="nickname" label="姓名"></el-table-column>
          <el-table-column prop="tel" label="联系电话"></el-table-column>
          <el-table-column prop="birthDate" label="生日"></el-table-column>
          <el-table-column prop="createTime" label="创建时间"></el-table-column>
          <el-table-column prop="updateTime" label="修改时间"></el-table-column>
          <el-table-column prop="roomNumber" label="入住房间">

          </el-table-column>
          <el-table-column prop="checkinDate" label="入住时间"></el-table-column>
          <el-table-column prop="idCard" label="身份证号码"></el-table-column>
          <el-table-column prop="familyName" label="绑定家属" width="250">
            <template #default="scope">
              <div v-if="scope.row.familyName">
                {{ scope.row.familyName}} ({{ scope.row.familyTel }})
              </div>
              <span v-else>未绑定</span>
            </template>
          </el-table-column>
          <el-table-column fixed="right" label="操作" width="320">
            <template #default="scope">
              <el-button :icon="Edit" @click="edit(scope.$index, scope.row)">编辑</el-button>
              <el-button
                type="primary"
                @click="showBindDialog(scope.row)"
                :icon="User"
              >绑定家属</el-button>
              <el-button :icon="Delete" type="danger" @click="deleteOne(scope.$index, scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <div style="margin-top: 20px">
          <el-pagination
                  @current-change="currentChange"
                  @size-change="sizeChange"
                  :page-size="pageInfo.pageSize"
                  :current-page="pageInfo.currentPage"
                  background
                  layout="total,sizes, prev, pager, next"
                  :total="pageInfo.total">
          </el-pagination>
        </div>
      </el-card>
    </el-space>
    <el-dialog
            v-model="dialogOpen"
            v-if="dialogOpen"
            :title="formData.id?'编辑':'新增'"
            width="500"
    >
      <el-form ref="formRef" :model="formData" label-width="100px">
        <slot name="content">
          <el-form-item label="用户 id" prop="userId" v-if="!formData.id" :rules="[{required:true,message:'不能为空',trigger:[ 'blur','change']}]">
            <el-input v-model="formData.userId"></el-input>
          </el-form-item>
          <el-form-item label="联系电话" prop="tel"  :rules="[{required:true,message:'不能为空',trigger:[ 'blur','change']}]">
            <el-input v-model="formData.tel"></el-input>
          </el-form-item>
          <el-form-item label="生日" prop="birthDate"  :rules="[{required:true,message:'不能为空',trigger:[ 'blur','change']}]">
            <el-input v-model="formData.birthDate"></el-input>
          </el-form-item>
          <el-form-item label="入住时间" prop="checkinDate" v-if="!formData.id" :rules="[{required:true,message:'不能为空',trigger:[ 'blur','change']}]">
            <el-input v-model="formData.checkinDate"></el-input>
          </el-form-item>
          <el-form-item label="身份证号码" prop="idCard"  :rules="[{required:true,message:'不能为空',trigger:[ 'blur','change']}]">
            <el-input v-model="formData.idCard"></el-input>
          </el-form-item>
          <el-form-item label="入住房间" prop="roomId" :rules="[{required:true,message:'请选择房间',trigger:'change'}]">
              <el-select
                  v-model="formData.roomId"
                  placeholder="请选择房间"
                  style="width: 100%"
                  @change="val => formData.buildingId = roomList.find(r => r.id === val)?.buildingId"
              >
              <el-option
                v-for="room in roomList"
                :key="room.id"
                :label="room.roomNumber"
                :value="room.id"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item v-show="false" prop="buildingId">
            <el-input v-model="formData.buildingId"></el-input>
          </el-form-item>
        </slot>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submit" :icon="Check">提交</el-button>
          <el-button @click="closeDialog" :icon="Close">取消</el-button>
        </div>
      </template>
    </el-dialog>

    <el-dialog v-model="bindDialogVisible" title="绑定家属" :before-close="handleClose" width="500">
      <el-form :model="bindForm" label-width="100px">
        <el-form-item label="老人信息">
          <div class="elder-info">
            {{ currentElder.nickname }} ({{ currentElder.idCard }})
          </div>
        </el-form-item>
        <el-form-item
          label="选择家属"
          prop="familyId"
          :rules="[{required:true,message:'请选择家属',trigger:'change'}]"
        >
          <el-select
            v-model="bindForm.familyId"
            placeholder="请选择家属"
            filterable
            remote
            :remote-method="searchFamily"
            :loading="familyLoading"
          >
            <el-option
              v-for="family in familyList"
              :key="family.id"
              :label="`${family.nickname} (${family.tel})`"
              :value="family.id"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="submitBind">提交绑定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import request from "@/utils/http.js";
import {Check, Close, Delete, Edit, Refresh, Plus, Search, User} from '@element-plus/icons-vue'
import {ref, toRaw, onMounted, reactive} from "vue";
import {ElMessage, ElMessageBox} from "element-plus";

const searchFormComponents = ref();
const tableComponents = ref();
const listData = ref([]);
const pageInfo = ref({
  //当前页
  pageNum: 1,
  //分页大小
  pageSize: 10,
  //总条数
  total: 0
});
const searchForm = ref({

});

// 新增房间相关数据
const roomList = ref([])
const roomMap = ref({})

// 获取房间列表
async function getRoomList() {
  try {
    const res = await request.get('/room/list')
    roomList.value = res.data
    roomMap.value = res.data.reduce((acc, cur) => {
      acc[cur.id] = cur
      return acc
    }, {})
  } catch (e) {
    console.error('获取房间列表失败:', e)
    ElMessage.error('房间数据加载失败')
  }
}

onMounted(() => {
  getPageList()
  getRoomList()
})

getPageList()


/**
 * 获取分页数据
 */
function getPageList() {
  let data = Object.assign(toRaw(searchForm.value), toRaw(pageInfo.value))
  request.get("/elder/page", {
    params: data
  }).then(res => {
    listData.value = res.data.list
    pageInfo.value.total = res.data.total
  })
}

/**
 * 选择分页
 * @param e
 */
function currentChange(e) {
  pageInfo.value.pageNum = e
  getPageList()
}

/**
 * 改变分页数量
 * @param e
 */
function sizeChange(e) {
  pageInfo.value.pageSize = e
  getPageList()
  console.log(e)
}

/**
 * 搜索
 */
function search() {
  pageInfo.value.pageNum = 1
  getPageList()
}

/**
 * 重置搜索框
 */
function resetSearch() {
  searchFormComponents.value.resetFields();
  getPageList()
}

const dialogOpen = ref(false);
const formData = ref({});
const formRef = ref();

/**
 * 新增
 */
function add() {
  formData.value = {}
  dialogOpen.value = true
}
/**
 * 编辑
 * @param index
 * @param row
 */
function edit(index, row) {
  formData.value = {
    ...row,
    buildingId: roomMap.value[row.roomId]?.buildingId // 初始化楼栋ID
  }
  dialogOpen.value = true
}
/**
 * 关闭弹框
 */
function closeDialog() {
  dialogOpen.value = false
}

/**
 * 提交数据
 */
function submit() {
  formRef.value.validate((valid) => {
    if (!valid){
      ElMessage({
        message: "验证失败，请检查表单!",
        type: 'warning'
      });
      return
    }
    //新增
    if (!formData.value.id) {
      request.post("/elder/add", formData.value).then(res => {
        if (!res) {
          return
        }
        dialogOpen.value = false
        ElMessage({
          message: "操作成功",
          type: 'success'
        });
        getPageList()
      })
    } else {
      //更新
      request.put("/elder/update", formData.value).then(res => {
        if (!res) {
          return
        }
        dialogOpen.value = false
        ElMessage({
          message: "操作成功",
          type: 'success'
        });
        getPageList()
      })
    }
  })
}
const selectionRows = ref([]);

/**
 * 多选
 * @param rows
 */
function selectionChange(rows) {
  selectionRows.value = rows
}

/**
 * 单个删除
 * @param index
 * @param row
 */
function deleteOne(index, row) {
  batchDelete([row])
}

/**
 * 批量删除
 * @param rows
 */
function batchDelete(rows) {
  if (!rows) {
    rows = selectionRows.value;
  }
  let ids = rows.map(item => item.id);
  ElMessageBox.confirm(`此操作将永久删除ID为[${ids}]的数据, 是否继续?`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
    center: true
  }).then(() => {
    request.delete("/elder/delBatch", {data: ids}).then(res => {
      if (!res) {
        return
      }
      ElMessage({
        message: "操作成功",
        type: 'success'
      });
      getPageList()
    })
  }).catch(() => {
    ElMessage({
      type: 'info',
      message: '已取消删除'
    });
    tableComponents.value.clearSelection();
  });
}

const bindDialogVisible = ref(false)


function handleClose(){
    console.log("1111")
    bindDialogVisible.value = false

    // currentElder.value = {}
    // bindForm.elderId = null
}


const currentElder = ref({})
const bindForm = reactive({
  elderId: null,
  familyId: null
})

const familyList = ref([])
const familyLoading = ref(false)

const showBindDialog = async (row) => {
  currentElder.value = row
  bindForm.elderId = row.id
  bindDialogVisible.value = true
  await loadFamilyList()
}

const loadFamilyList = async () => {
  try {
    familyLoading.value = true
    const res = await request.get('/family/list', {
      params: { elderId: currentElder.value.id }
    })
    familyList.value = res.data
  } catch (error) {
    console.error('获取家属列表失败:', error)
    ElMessage.error('获取家属列表失败')
  } finally {
    familyLoading.value = false
  }
}

const submitBind = async () => {
  try {
    await request.post('/elder/bindFamily', {
      id: bindForm.elderId,
      familyId: bindForm.familyId
    })
    ElMessage.success('绑定成功')
    bindDialogVisible.value = false
    Object.assign(bindForm, {
      elderId: null,
      familyId: null
    })

      window.location.reload()
    getPageList()
  } catch (error) {
    console.error('绑定失败:', error)
    ElMessage.error(error.response?.data?.message || '绑定失败')
  }
}

const searchFamily = async (query) => {
  if (!query) return
  try {
    familyLoading.value = true
    const res = await request.get('/family/search', {
      params: { keyword: query }
    })
    familyList.value = res.data
  } catch (error) {
    console.error('搜索家属失败:', error)
  } finally {
    familyLoading.value = false
  }
}


</script>

<style scoped>
/* 添加家属标签样式 */
.family-tag {
  margin: 4px;
  padding-right: 25px;
  position: relative;
}
.family-tag .el-icon {
  position: absolute;
  right: 5px;
  top: 50%;
  transform: translateY(-50%);
  cursor: pointer;
  color: #999;
}
.family-tag .el-icon:hover {
  color: #ff4d4f;
}

.bind-family-container {
  display: grid;
  gap: 20px;
}

.family-list {
  max-height: 300px;
  overflow-y: auto;
}

.bind-form {
  margin-top: 20px;
}

.elder-info {
  padding: 8px;
  background: #f5f7fa;
  border-radius: 4px;
}

.card-header {
  font-weight: 600;
  color: #303133;
}
</style>
